package org.bingo.web.exception;

import org.bingo.constant.HttpStatus;
import org.bingo.entity.ReturnInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author mj
 * @version 1.0
 * @date 2022/2/28 0028 下午 22:13
 * 全局异常处理器
 **/
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理方法不支持
     * @param e 异常类
     * @param request  HttpServletRequest
     * @return 错误信息
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ReturnInfo handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                          HttpServletRequest request){
        String uri = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求",uri,e.getMethod());
        return ReturnInfo.fail(HttpStatus.Method_Not_Allowed,e.getMessage());
    }

    /**
     * 处理系统异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ReturnInfo handleException(Exception e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常'{}'", requestURI, e);
        return ReturnInfo.fail(HttpStatus.Internal_Server_Error,e.getMessage());
    }

    /**
     * 处理未知运行时异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public ReturnInfo handleRuntimeException(RuntimeException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常'{}'", requestURI, e);
        return ReturnInfo.fail(HttpStatus.Internal_Server_Error,e.getMessage());
    }


}
